package stfin.install.composite;

import java.io.IOException;
import java.util.ResourceBundle;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import stfin.install.utility.Installator;

public class InstallMain extends Composite{

	private Installator installator;
	private Button removeDataCheck;
	private ResourceBundle bundle;
	
	
	public InstallMain(Composite parent, int style) throws IOException {
		super(parent, style);
		try {
			installator = new Installator();
			bundle = installator.getBundle();
			initContents();
		} catch (IOException e) {
			MessageBox messageBox = new MessageBox(getShell(), SWT.ERROR);
			messageBox.setText("ERROR");
			messageBox.setMessage(e.getLocalizedMessage());
			messageBox.open();
			throw e;
		}

	}

	private void initContents() {

		final boolean installed = installator.isInstalled();

		setLayout(new FormLayout());

		Composite composite = new Composite(this, SWT.NONE);
		composite.setBackground(new Color(getDisplay(), new RGB(255,255,255)));
		composite.setLayout(new FormLayout());

		FormData formData = new FormData();
		formData.top = new FormAttachment(0);
		formData.left = new FormAttachment(0);
		formData.right = new FormAttachment(15);
		formData.bottom = new FormAttachment(100);

		composite.setLayoutData(formData);

		Label separator = new Label(this, SWT.SEPARATOR | SWT.VERTICAL);

		formData = new FormData();
		formData.top = new FormAttachment(0);
		formData.left = new FormAttachment(16,-12);
		formData.right = new FormAttachment(17);
		formData.bottom = new FormAttachment(100);
		separator.setLayoutData(formData);

		composite = new Composite(this, SWT.NONE);
		composite.setLayout(new GridLayout(3,false));

		formData = new FormData();
		formData.top = new FormAttachment(0);
		formData.left = new FormAttachment(18);
		formData.right = new FormAttachment(100);
		formData.bottom = new FormAttachment(85);

		composite.setLayoutData(formData);

		Label warnText = new Label(composite, SWT.WRAP);
		warnText.setText(bundle.getString("info-message"));

		GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalSpan = 3;
		warnText.setLayoutData(gridData);

		separator = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
		gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalSpan = 3;
		separator.setLayoutData(gridData);

		Label label = new Label(composite, SWT.NONE);
		
		if(installed){
			label.setText(bundle.getString("install-file.current-location"));
		}else{
			label.setText(bundle.getString("install-file.location"));
		}
		

		gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalSpan = 3;
		label.setLayoutData(gridData);

		gridData = new GridData();
		gridData.grabExcessHorizontalSpace = true;
		gridData.horizontalAlignment = GridData.FILL;
		gridData.horizontalSpan = 2;

		final Text text = new Text(composite, SWT.BORDER | SWT.READ_ONLY);
		text.setBackground(new Color(getDisplay(),new RGB(241,240, 239)));
		text.setLayoutData(gridData);

		text.setText(installator.getDefaultInstallationDir());

		Button button = new Button(composite, SWT.PUSH);
		button.setText("...");
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				DirectoryDialog databaseDirDialog = new DirectoryDialog(getShell());
				text.setText(databaseDirDialog.open());
			}
		});

		button.setEnabled(!installed);

		gridData = new GridData();
		button.setLayoutData(gridData);

		label = new Label(composite, SWT.NONE);
		if(installed){
			label.setText(bundle.getString("install-file.current-data-location"));
		}else{
			label.setText(bundle.getString("install-file.data-location"));
		}

		gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalSpan = 3;
		label.setLayoutData(gridData);

		gridData = new GridData();
		gridData.grabExcessHorizontalSpace = true;
		gridData.horizontalAlignment = GridData.FILL;
		gridData.horizontalSpan = 2;

		final Text text2 = new Text(composite, SWT.BORDER | SWT.READ_ONLY);
		text2.setBackground(new Color(getDisplay(),new RGB(241,240, 239)));
		text2.setLayoutData(gridData);

		text2.setText(installator.getInstallationDataDir());

		button = new Button(composite, SWT.PUSH);
		button.setText("...");
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				DirectoryDialog databaseDirDialog = new DirectoryDialog(getShell());
				text2.setText(installator.normalizeDataDir(databaseDirDialog.open()));
			}
		});

		button.setEnabled(!installed);

		gridData = new GridData();
		button.setLayoutData(gridData);

		
		if(installed){
			removeDataCheck = new Button(composite, SWT.CHECK);
			removeDataCheck.setText(bundle.getString("installation.remove-data"));

			gridData = new GridData();
			gridData.horizontalSpan = 3;
			removeDataCheck.setLayoutData(gridData);
		}

		separator = new Label(this, SWT.SEPARATOR | SWT.HORIZONTAL);

		formData = new FormData();
		formData.top = new FormAttachment(86);
		formData.left = new FormAttachment(16);
		formData.right = new FormAttachment(100);
		formData.bottom = new FormAttachment(87);
		separator.setLayoutData(formData);


		composite = new Composite(this, SWT.RIGHT_TO_LEFT);
		RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL);
		rowLayout.center = true;
		rowLayout.pack = false;
		composite.setLayout(rowLayout);

		formData = new FormData();
		formData.top = new FormAttachment(88);
		formData.left = new FormAttachment(31);
		formData.right = new FormAttachment(100);
		formData.bottom = new FormAttachment(100);

		composite.setLayoutData(formData);

		button = new Button(composite, SWT.PUSH);
		button.setText(installed ? bundle.getString("uninstall") : bundle.getString("install"));
		button.setLayoutData(new RowData());

		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				try {

					if(installed){
						installator.uninstall(removeDataCheck.getSelection());
					}else{
						installator.install(text.getText(), text2.getText());
					}

				MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION);
				messageBox.setText("Informações de Instalação");
				messageBox.setMessage(installed ? "Statízo Desinstalado com sucesso" : "Statízo Instalado com sucesso");
				messageBox.open();
				
				getParent().dispose();
					
				} catch (IOException e1) {
					MessageBox messageBox = new MessageBox(getShell(), SWT.ERROR);
					messageBox.setText("Erro ao instalar.");
					messageBox.setMessage("Erro na instalação " + e1.getMessage());
					messageBox.open();
				}
			}
		});

		button = new Button(composite, SWT.PUSH);
		button.setText(bundle.getString("cancel"));
		button.setLayoutData(new RowData());
		button.setFocus();

	}

	public static void main(String[] args) throws IOException {

		Display display = Display.getDefault();
		Shell dialog = new Shell(display, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);

		dialog.setLayout(new RowLayout());
		dialog.setSize(650,550);
		dialog.setText("Instalação");

		Monitor primary = display.getPrimaryMonitor();
		Rectangle bounds = primary.getBounds();
		Rectangle rect = dialog.getBounds();

		int x = bounds.x + (bounds.width - rect.width) / 2;
		int y = bounds.y + (bounds.height - rect.height) / 2;

		dialog.setLocation(x, y);

		InstallMain installMain = new InstallMain(dialog, SWT.NONE);
		installMain.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));

		dialog.setLayout(new GridLayout());
		//dialog.pack();
		dialog.open();

		while (!dialog.isDisposed()) { 
			if (!display.readAndDispatch()) display.sleep(); 
		} 

	}

	public String getWarning(){
		StringBuilder str = new StringBuilder();
		str.append("Este instalador não cria um serviço no seu computador\n");
		str.append("Não obstante, é recomendado que você crie um ponto de restauração\nsempre que instalar um novo aplicativo.\n");
		str.append("(caso o seu Sistema Operacional possua essa opção).");
		return str.toString();
	}

}
